package com.skytech.component.monitor.task;

import com.alibaba.fastjson.JSONObject;
import com.skytech.component.monitor.enterprise_data_monitoring.JiangSuService;
import com.skytech.component.monitor.util.ChromeBrowser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class PartTask {

    @Autowired
    private ChromeBrowser chromeBrowser;

    @Autowired
    private JiangSuService jiangSuService;

    private static final Logger log = LoggerFactory.getLogger(PartTask.class);

    private List<JSONObject> jsonObjects;

    private int threadNum=1;

    private AtomicInteger scriptIndex;


    public void setThreadNum(int threadNum) {
        this.threadNum = threadNum;
    }

    public void init(List<JSONObject> jsonObjects) {
        this.jsonObjects = jsonObjects;
        scriptIndex = new AtomicInteger(jsonObjects.size());
    }

    public void rush(){
        List<Thread> threadList = new ArrayList<>();
        for (int i = 0; i < threadNum; i++) {
            ThreadShell shell = new ThreadShell((l) ->{
                consumer(l);
            },String.valueOf(i));

            Thread thread = new Thread(shell);
            thread.start();
            threadList.add(thread);
        }

    }
    public  int next(){
        return this.scriptIndex.decrementAndGet();
    }

    private void consumer(String name){
        int index = next();
        if(index>=0){
            log.error("第{}条线程开始",name);
            jiangSuService.enterpriseData(chromeBrowser.getChromeDriver(), Arrays.asList(jsonObjects.get(index)));
            consumer(name);
        }
    }




}
